package com.fan.shop.businesslogic;

import org.apache.log4j.Logger;

import com.fan.shop.domain.PurchaseLine;
import com.fan.shop.domain.PurchaseOrder;
import com.fan.shop.domain.Stock;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.process.ProcExec;
import com.fan.shop.services.PurchaseOrderService;
import com.fan.shop.services.StockService;

public class PurchaseOrderCompleteProcess extends ProcExec<Integer> {

	private static Logger logger = Logger
			.getLogger(PurchaseOrderCompleteProcess.class);
	private PurchaseOrderService purchaseOrderService;
	private StockService stockService;
	private String poNumber;
	private String comments;

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		PurchaseOrderCompleteProcess.logger = logger;
	}

	public PurchaseOrderService getPurchaseOrderService() {
		return purchaseOrderService;
	}

	public void setPurchaseOrderService(
			PurchaseOrderService purchaseOrderService) {
		this.purchaseOrderService = purchaseOrderService;
	}

	public StockService getStockService() {
		return stockService;
	}

	public void setStockService(StockService stockService) {
		this.stockService = stockService;
	}

	public String getPoNumber() {
		return poNumber;
	}

	public void setPoNumber(String poNumber) {
		this.poNumber = poNumber;
	}

	public String getComments() {
		return comments;
	}

	public void setComments(String comments) {
		this.comments = comments;
	}

	@Override
	public Integer processImpl() {

		PurchaseOrder purchaseOrder = purchaseOrderService
				.getPurchaseOrder(poNumber);
		purchaseOrder.setStatus(ShopGlobalVariables.COMPLETED);
		purchaseOrder.setComments(comments);

		try {
			for (PurchaseLine purchaseLine : purchaseOrderService
					.getPurchaseLines(poNumber)) {
				Stock stock = stockService.getStock(purchaseLine.getId()
						.getItemCode(), purchaseOrder.getStoreCode());
				int requestedQty = purchaseLine.getQuantity();
				int holdQty = stock.getHoldQty();
				int newHoldQty = holdQty - requestedQty;
				if (newHoldQty < 0) {
					setErrorMessage("Current Stock: "
							+ stock.getId().getItemCode() + "@"
							+ purchaseOrder.getStoreCode()
							+ " doesn't have enough quantity!");
					return ShopGlobalVariables.FAILED;
				} else {
					stock.setHoldQty(newHoldQty);
					stockService.updateStock(stock);
				}
			}

			purchaseOrderService.updatePurchaseOrder(purchaseOrder);
		} catch (Exception e) {
			setErrorMessage("Failed updating Purchase Order");
			return ShopGlobalVariables.FAILED;
		}
		return ShopGlobalVariables.SUCCESS;
	}

}
